package com.med.meddataintegrator.jwt.handle;

import com.med.meddataintegrator.common.basic.response.JsonResult;
import com.med.meddataintegrator.jwt.pojo.LoginUserInfoVo;
import com.med.meddataintegrator.jwt.utils.JwtUtil;
import com.med.meddataintegrator.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 根据认证过后的用户信息 生成返回的Token信息
     */
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //拿到认证过后的用户信息
        Object principal = authentication.getPrincipal();
        LoginUserInfoVo userInfoVo = null;

        if (principal != null && principal instanceof LoginUserInfoVo){
            userInfoVo = (LoginUserInfoVo) principal;

        }
            //生成Token 根据用户名
        String token = jwtUtil.createJwt(userInfoVo.getUserDo().getUsername());
        log.info("用户名:{} 生成Token:{}",userInfoVo.getUserDo().getUsername(),token);

        ResultUtil.ok(response, JsonResult.ok(token));

    }


}
